package com.wzx.web;

import com.wzx.domain.Person;
import com.wzx.service.IPersonService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(LoginServlet.class);
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取账号密码
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        logger.debug(username);
        logger.debug(password);
        //从配置文件中取数据 .properties  Properties
        Properties p = new Properties();
        InputStream is = LoginServlet.class.getClassLoader().getResourceAsStream("info.properties");
        p.load(is);
        //调用登录方法

        //我们需要做的是  在servlet中，使用api获取ioc容器，就可以进一步获取与使用service

        // ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(p.getProperty("config"));
        //1:从ServletContext域对象获取Spring容器
        WebApplicationContext context = (WebApplicationContext) getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        IPersonService personService = (IPersonService) context.getBean(p.getProperty("serviceId"));
        Person person = new Person(username,password);

        boolean flag = personService.login(person);
        logger.debug(flag+" doGet ");
        //结果
        response.getWriter().println(flag?"success":"error");
    }
}
